#include "CTextEdit.h"
#include "EventHelper.h"

#include <QApplication>
#include <QEvent>
#include <QKeyEvent>

CTextEdit::CTextEdit(QWidget *parent) : QPlainTextEdit(parent) {
}

CTextEdit::CTextEdit(const QString &text, QWidget *parent) : QPlainTextEdit(text, parent) {
}

void CTextEdit::setText(const QString &text) {
    setPlainText(text);
}

QString CTextEdit::text() const {
    return toPlainText();
}

bool CTextEdit::event(QEvent *event) {
    if (Ev::keyIsDown(event)) {
        QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
        int key = keyEvent->key();
        if ((key == Qt::Key_Return || key == Qt::Key_Enter) &&
            QApplication::keyboardModifiers() == Qt::ControlModifier) {
            editFinish();
            return true;
        }
    }
    return QPlainTextEdit ::event(event);
}

void CTextEdit::focusOutEvent(QFocusEvent *event) {
    QPlainTextEdit::focusOutEvent(event);
    emit loseFocus();
    editFinish();
}

void CTextEdit::editFinish() {
    if (hasFocus()) {
        clearFocus();
    }
    emit editFinished();
}
